<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="_fetchGlobalParams"
    :columns="columns"
    :row-selection="rowSelection"
    row-key="configId"
  >
    <template #toolbars>
      <Row class="w-full mr-3">
        <Col :span="16">
          <Space>
            <b-button icon="add" @click="onAdd" code="system:config:add"
              >新增</b-button
            >
            <b-button
              icon="delete"
              @click="onDelete"
              :disabled="!selectKeys?.length"
              code="system:config:remove"
              >删除</b-button
            >
          </Space>
        </Col>
        <Col :span="8" class="text-right content-center">
          <Space>
            <b-button
              icon="export"
              @click="onExport"
              code="system:config:export"
              >导出</b-button
            >
          </Space>
        </Col>
      </Row>
    </template>
    <template #operation="{ record }">
      <b-button icon="detail" type="link" @click="() => onView(record)"
        >详情</b-button
      >
    </template>
  </ProTable>
  <FormModal :items="items"> </FormModal>
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue';
import { Col, Modal, Row, Space, Tag } from 'ant-design-vue';
import dayjs from 'dayjs';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { download, listToEnum, listToOption } from '@/utils/utils';
import { fetchIsSystemInner } from '@/api/dict';
import {
  createGlobalParams,
  deleteGlobalParams,
  exportGlobalParams,
  fetchGlobalParams,
  updateGlobalParams,
} from '@/api/system';
import { hasPermission } from '../../../permission';

const tableRef = ref();

const isSysInnerOptions = ref<Global.Option[]>([]);
const isSysInnerEnum = ref<Record<string, any>>([]);

const init = () => {
  fetchIsSystemInner().then((res) => {
    isSysInnerOptions.value = listToOption(
      res.data,
      'dictLabel',
      'dictValue',
    ) as Global.Option[];
    isSysInnerEnum.value = listToEnum(
      res.data as any,
      'dictValue',
      'dictLabel',
    );
  });
};

init();

const _fetchGlobalParams = async (params: any) => {
  params.params = {
    beginTime: params.time?.[0],
    endTime: params.time?.[1],
  };
  const res = await fetchGlobalParams(params);
  return res;
};
const selectKeys = ref<number[]>([]);
const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectKeys.value,
    onChange(values, all) {
      selectKeys.value = values as number[];
    },
  };
});

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '参数主键',
    dataIndex: 'configId',
    hideInSearch: true,
  },
  {
    title: '参数名称',
    dataIndex: 'configName',
  },
  {
    title: '参数键名',
    dataIndex: 'configKey',
  },
  {
    title: '参数键值',
    dataIndex: 'configValue',
    hideInSearch: true,
  },
  {
    title: '创建时间',
    dataIndex: 'time',
    isTime: true,
    hideInTable: true,
  },
  {
    title: '系统内置',
    dataIndex: 'configType',
    valueEnum: {
      ...isSysInnerEnum.value,
    },
    customRender({ text }) {
      return (
        <Tag color={text === 'Y' ? 'processing' : 'error'}>
          {isSysInnerEnum.value[text] || text}
        </Tag>
      );
    },
  },
  {
    title: '备注',
    dataIndex: 'remark',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 100,
  },
]);

const items = computed<ProFormProps['items']>(() => [
  {
    label: '参数名称',
    type: 'input',
    field: 'configName',
    rules: [{ required: true, message: '请输入参数名称', trigger: 'blur' }],
    props: {
      placeholder: '请输入参数名称',
    },
  },
  {
    label: '参数键名',
    type: 'input',
    field: 'configKey',
    rules: [{ required: true, message: '请输入参数键名', trigger: 'blur' }],
    props: {
      placeholder: '请输入参数键名',
    },
  },
  {
    label: '参数键值',
    type: 'input',
    field: 'configValue',
    rules: [{ required: true, message: '请输入参数键值', trigger: 'blur' }],
    props: {
      placeholder: '请输入参数键值',
    },
  },
  {
    label: '系统内置',
    type: 'radio',
    field: 'configType',
    rules: [{ required: true, message: '请选择是否系统内置', trigger: 'blur' }],
    props: {
      options: isSysInnerOptions.value,
    },
  },
  {
    label: '备注',
    type: 'textarea',
    field: 'remark',
    props: {
      placeholder: '请输入备注',
      showCount: true,
      maxlength: 200,
    },
  },
]);

const { FormModal, open } = useFormModal({ size: 'small' });

const onAdd = async () => {
  open({
    title: '新增',
    defaultValue: {
      configType: '0',
    },
    serviceApi: async (params: any): Promise<any> => {
      await createGlobalParams(params);
      sleep(() => tableRef.value.refresh());
    },
  });
};

const onView = async (record: any) => {
  open({
    title: (type) => (type === 'info' ? '详情' : '编辑'),
    modalType: 'info',
    defaultValue: {
      ...record,
    },
    hasEditPermission: hasPermission('system:config:edit'),
    serviceApi: async (params: any): Promise<any> => {
      await updateGlobalParams({
        ...params,
        id: record.id,
      });
      sleep(() => tableRef.value.refresh());
    },
  });
};
const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};

const onDelete = async () => {
  Modal.confirm({
    title: '系统提示',
    content: `确认要删除当前选项？`,
    onOk: async () => {
      await deleteGlobalParams(selectKeys.value);
      sleep(() => tableRef.value.refresh());
      selectKeys.value = [];
    },
  });
};

const onExport = async () => {
  const res = await exportGlobalParams();
  download(
    res as unknown as Blob,
    `data_${dayjs().format('YYYY-MM-DD HH:mm:ss')}.xlsx`,
  );
};
</script>
